package com.loongtech.bi.action.system;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.loongtech.bi.entity.system.EntitySysRole;
import com.loongtech.bi.manager.system.SysLogManager;
import com.loongtech.bi.manager.system.SysRoleManager;
import com.loongtech.bi.support.Session;

/**
 * 增加角色
 * 
 * @author xckuang
 * @date 2014-10-06
 */
@Controller("roleRegisterAction")
@Scope("view")
public class RoleRegisterAction implements Serializable {
	private static final long serialVersionUID = 1L;
	@Autowired
	private Session session;
	@Autowired
	private SysRoleManager sysRoleManager;
	@Autowired
	private SysLogManager sysLogManager;
	private EntitySysRole role;
	private static final String FailTag = "增加角色失败";
	private static final String SuccTag = "增加角色成功";

	@Autowired
	public void init() {
		setRole(new EntitySysRole());
	}

	public void add() {
		FacesContext context = FacesContext.getCurrentInstance();

		// 判断参数
		String username = role.getName();
		if(null == username || username.isEmpty()) {
			context.addMessage(null, new FacesMessage(FailTag, "角色名为空!"));
			return;
		}
		// 判断用户username是否已经被注册
		if(null != sysRoleManager.getBy(EntitySysRole.K.name, username)) {
			context.addMessage(null, new FacesMessage(FailTag, "名称已注册!"));
			return;
		}
		
		// 注册用户
		try {
			sysRoleManager.persist(role);
			context.addMessage(null, new FacesMessage(SuccTag, "角色名称为" + username));
			sysLogManager.addLog(session.getUserName(), SuccTag + username);
			setRole(new EntitySysRole());
		} catch(Exception ex) {
			context.addMessage(null, new FacesMessage(FailTag, "注册时发生异常!"));
			return;
		}
	}

	public EntitySysRole getRole() {
		return role;
	}

	public void setRole(EntitySysRole role) {
		this.role = role;
	}
}
